# coding: utf8
import time
import uuid

import tornado
from tornado import gen

import cms_config
from app.base_controller import BaseController
from app.common import global_space, wzhifuSDK
from app.models import Goods, Feedback, GCategory, Comment, User, Price, GOrder
from libs.util import check_param
from django.db.models import Q


# /api/goods-list
class GoodList(BaseController):
    def get(self):
        category = self.get_argument("category", '')

        if not category:
            gc = GCategory.objects.filter(state=0).order_by('show_order').first()
        else:
            gc = GCategory.objects.filter(state=0).filter(id=category).order_by('show_order').first()
        vo = Goods.objects.filter(state=0).filter(category=gc). \
            prefetch_related('prices'). \
            prefetch_related('banners')
        order = self.get_argument("order", '')
        if order and 'sales' in order:
            vo = vo.order_by(order)
        elif 'price' in order:
            _list = [key.to_dict(photo_style='/350_320') for key in vo.all()]
            if order == 'price':
                _list.sort(key=lambda k: (k.get('price').get('transaction_price')))
            if order == '-price':
                _list.sort(key=lambda k: (-k.get('price').get('transaction_price')))
            paginator = self.pagination_list(object_list=_list, page_num=int(self.get_argument("pageNum", 1)))
            return self.render_json(data=paginator)
        else:
            vo = vo.order_by('show_order', '-update_time')

        paginator = self.pagination(vo.all(), page_num=int(self.get_argument("pageNum", 1)), photo_style='/350_320')

        paginator['cateory'] = gc.to_dict()
        return self.render_json(data=paginator)



class GoodCategory(BaseController):
    def get(self):
        self.render_json(data=[key.to_dict() for key in GCategory.objects.filter(state=0).order_by('show_order').all()])


# /api/goods-top
class GoodTop(BaseController):
    def get(self):
        vo = Goods.objects.filter(state=0). \
            prefetch_related('prices'). \
            prefetch_related('banners')
        vo = vo.order_by('show_order', '-update_time')
        paginator = self.pagination(vo.all(), number_per_page=4, page_num=int(self.get_argument("pageNum", 1)), photo_style='/350_320')
        return self.render_json(data=paginator)


#/api/goods-detail
class GoodDetail(BaseController):
    def get(self):
        id = self.get_argument("id", 1)
        vo = Goods.objects.filter(id=id). \
            prefetch_related('prices'). \
            prefetch_related('banners').first()
        return self.render_json(data=vo.to_dict(type=2, photo_style='/350_320'))


# /goods-comment
class CommentList(BaseController):
    def get(self):
        goods_id = self.get_argument("goods_id")

        param = [goods_id]
        if check_param(param):
            self.render_json(code=1001, msg='参数不全')
            return
        vo = Comment.objects
        good = Goods.objects.filter(id=goods_id).first()
        if not good:
            self.render_json(code=1001, msg='参数不正确')
            return
        vo = vo.filter(goods=good). \
            select_related('price').select_related('goods'). \
            select_related('user').order_by("-create_time")
        paginator = self.pagination(vo.all(), page_num=int(self.get_argument("pageNum", 1)), photo_style='/350_320')
        return self.render_json(data=paginator)


class OrderConfirm(BaseController):
    def post(self):
        id = self.get_json_argument("id", '')
        remark = self.get_json_argument("remark", '')
        session_id = self.get_json_argument("session_id", '')

        param = [id, session_id]
        if check_param(param):
            self.render_json(code=1001, msg='参数不全')
            return
        vo = GOrder.objects.filter(id=id).first()
        if not vo:
            self.render_json(code=1001, msg='参数不对')
            return

        session = global_space.very_session(session_id)
        if not session:
            self.render_json(code=999, msg='session 失效')
            return

        if vo.status != 99:
            self.render_json(code=1004, msg='此状态不允许下单')
            return

        user = User.objects.filter(id=session['id']).first()
        if not user:
            return self.render_json(code=1001, msg='用户不存在')

        if vo.user.id != user.id:
            self.render_json(code=1009, msg='不能修改别人的订单')
            return
        vo.status = 1
        vo.remark = remark
        vo.save()
        return self.render_json(data={})


class OrderClose(BaseController):
    def post(self):
        id = self.get_json_argument("id", '')
        session_id = self.get_json_argument("session_id", '')

        param = [id, session_id]
        if check_param(param):
            self.render_json(code=1001, msg='参数不全')
            return
        vo = GOrder.objects.filter(id=id).first()
        if not vo:
            self.render_json(code=1001, msg='参数不对')
            return

        session = global_space.very_session(session_id)
        if not session:
            self.render_json(code=999, msg='session 失效')
            return

        if vo.status != 1:
            self.render_json(code=1004, msg='此状态不允许下单')
            return

        user = User.objects.filter(id=session['id']).first()
        if not user:
            return self.render_json(code=1001, msg='用户不存在')

        if vo.user.id != user.id:
            self.render_json(code=1009, msg='不能修改别人的订单')
            return
        vo.status = 14
        vo.save()
        return self.render_json(data={})
# 
# 
class OrderCreate(BaseController):
    def post(self):
        goods_id = self.get_json_argument("goods_id", '')
        price_id = self.get_json_argument("price_id", '')
        num = self.get_json_argument("num", 1)
        session_id = self.get_json_argument("session_id", '')
        param = [goods_id, price_id, num, session_id]
        if check_param(param):
            self.render_json(code=1001, msg='参数不全')
            return
        session = global_space.very_session(session_id)
        if not session:
            self.render_json(code=999, msg='session 失效')
            return

        user = User.objects.filter(id=session['id']).first()
        if not user:
            return self.render_json(code=1001, msg='用户不存在')

        goods = Goods.objects.filter(id=goods_id).first()
        price = Price.objects.filter(id=price_id).first()

        if not goods or not price:
            self.render_json(code=1001, msg='参数错误')
            return

        if price not in goods.prices.all():
            self.render_json(code=1001, msg='参数错误')
            return

        if price.inventory <= 0:
            self.render_json(code=1001, msg='库存不足')
            return

        fee = price.transaction_price * int(num)

        data_str = time.strftime('%Y%m%d%H%M%S', time.localtime())
        order_id = data_str + str(global_space.get_order_id()).zfill(32 - len(data_str))

        data_str = time.strftime('%Y', time.localtime())
        id = data_str + str(global_space.get_order_id()).zfill(10 - len(data_str))

        vo = GOrder.objects.create(id=id, status=99, goods=goods, price=price, pay_price=fee, pay_amount=0, user=user, num=num, order_id=order_id)

        self.render_json(data=dict(
            id=vo.id,
        ))
# 
# 
class PayNotify(BaseController):
    def post(self):
        # log.info(self.request.body)
        data = wzhifuSDK.xml_to_dict(self.request.body.decode('utf-8'))
        out_trade_no = data.get('out_trade_no')
        total_fee = data.get('total_fee')
        transaction_id = data.get('transaction_id')
        vo = GOrder.objects.filter(order_id=out_trade_no).first()
        vo.weixin_order_id = transaction_id
        vo.pay_amount = int(total_fee) / 100
        # if int(total_fee) / 100==vo.price:
        vo.status = 15
        vo.save()

        good_p = Price.objects.filter(id=vo.price.id).first()
        good_p.inventory = good_p.inventory - 1
        good_p.save()

        good = Goods.objects.filter(id=vo.goods.id).first()
        good.sales = good.sales + 1
        good.save()
        self.write('''<xml>
                    <return_code>SUCCESS</return_code>
                    <return_msg>OK</return_msg>
                    </xml>''')
# 
# 
class Pay(BaseController):
    @tornado.web.asynchronous
    def post(self):
        session_id = self.get_json_argument("session_id", '')
        if check_param(session_id):
            self.render_json(code=1001, msg='参数不全')
        session = global_space.very_session(session_id)
        if not session:
            self.render_json(code=999, msg='session 失效')
            return
        user = User.objects.filter(id=session['id']).first()
        if not user:
            return self.render_json(code=1001, msg='用户不存在')

        url = 'https://api.mch.weixin.qq.com/pay/unifiedorder'
        http = tornado.httpclient.AsyncHTTPClient()

        id = self.get_json_argument("id", '')
        remark = self.get_json_argument("remark", '')

        remote_ip = self.request.remote_ip
        param = [id, session_id]
        if check_param(param):
            self.render_json(code=1001, msg='参数不全')
            return
        vo = GOrder.objects.filter(id=id).first()

        if not vo:
            self.render_json(code=1008, msg='订单不存在')
            return
        if vo.status != 1:
            self.render_json(code=1004, msg='此状态不允许付款')
            return

        if vo.user.id != user.id:
            self.render_json(code=1009, msg='不能支付别人的订单')
            return
        if remark:
            vo.remark = remark
            vo.save()

        data = {"appid": cms_config.app_id,
                "openid": user.openid,
                "mch_id": cms_config.mch_id,
                "nonce_str": uuid.uuid1().hex,
                "body": vo.goods.name,
                "sign_type": "MD5",
                "out_trade_no": str(vo.order_id),
                "total_fee": str(1),
                "spbill_create_ip": remote_ip,
                "notify_url": "https://api.joyfulmedia.cn/api/goods-order-notify",
                "trade_type": "JSAPI"
                }

        sign = wzhifuSDK.get_sign(data)
        data['sign'] = sign
        http.fetch(url, method='POST', body=wzhifuSDK.trans_dict_to_xml(data),
                   callback=self.on_response)

    def on_response(self, response):
        if response.error:
            self.render_json(code=1002, msg='系统异常')
        else:
            sign_data = {}
            data = wzhifuSDK.xml_to_dict(response.body.decode('utf-8'))
            if data.get('return_code', '') == 'SUCCESS' and data.get('return_msg', '') == 'OK' and data.get('result_code', '') == 'SUCCESS':
                sign_data['nonceStr'] = uuid.uuid1().hex.upper()
                sign_data['signType'] = 'MD5'
                sign_data['timeStamp'] = str(int(time.time()))
                sign_data['appId'] = cms_config.app_id
                sign_data['package'] = 'prepay_id=' + data.get('prepay_id', '')
                sign_data['sign'] = wzhifuSDK.get_sign(sign_data)
                self.render_json(data=sign_data)
            else:
                self.render_json(code=9999, msg='系统错误')


class Comments(BaseController):
    def post(self):
        id = self.get_json_argument("id", '')

        remark = self.get_json_argument("remark", '')
        session_id = self.get_json_argument("session_id", '')
        param = [id, session_id, remark]
        if check_param(param):
            self.render_json(code=1001, msg='参数不全')
        session = global_space.very_session(session_id)
        if not session:
            self.render_json(code=999, msg='session 失效')
            return

        user = User.objects.filter(id=session['id']).first()
        if not user:
            return self.render_json(code=1001, msg='用户不存在')

        vo = GOrder.objects.filter(id=id).first()
        if not vo:
            self.render_json(code=1008, msg='订单不存在')
            return
        if vo.status != 9:
            self.render_json(code=1004, msg='此状态不允许评论')
            return
        if vo.user.id != user.id:
            self.render_json(code=1009, msg='不能修改别人的订单')
            return
        vo.status = 13
        vo.save()
        Comment.objects.create(goods=vo.goods, content=remark, price=vo.good_price, user=user)
        return self.render_json(data={})

# 
class Detail(BaseController):
    def get(self):
        id = self.get_argument("id", '')
        session_id = self.get_argument("session_id", '')
        param = [id, session_id]
        if check_param(param):
            self.render_json(code=1001, msg='参数不全')
            return
        session = global_space.very_session(session_id)
        if not session:
            self.render_json(code=999, msg='session 失效')
            return

        vo = GOrder.objects.filter(id=id).select_related('goods').select_related('price').first()

        user = User.objects.filter(id=session['id']).first()
        if not user:
            return self.render_json(code=1001, msg='用户不存在')

        if vo.user.id != user.id:
            self.render_json(code=1009, msg='不能查看别人的订单')
            return
        self.render_json(data=vo.to_dict())


class List(BaseController):
    def get(self):
        session_id = self.get_argument("session_id", '')
        if check_param(session_id):
            self.render_json(code=1001, msg='参数不全')
        session = global_space.very_session(session_id)
        if not session:
            self.render_json(code=999, msg='session 失效')
            return
        user = User.objects.filter(id=session['id']).first()
        if not user:
            return self.render_json(code=1001, msg='用户不存在')

        vo = GOrder.objects.filter(user=user).filter(~Q(status__in=[99,14])).select_related('goods').select_related('price').order_by('-create_time')
        paginator = self.pagination(vo.all(), page_num=int(self.get_argument("pageNum", 1)), photo_style='/710_476')
        return self.render_json(data=paginator)



